<?php
declare (strict_types = 1);
namespace app\admin\model;
use app\admin\model\AdminUserRole as AdminUserRoleModel;
use app\admin\model\AdminRole as AdminRoleModel;
/**
 * 超管列表模型
 */
class AdminUser extends BaseModel
{
	
	// 定义表名
    protected $name = 'admin_user';

    // 定义主键
    protected $pk = 'admin_user_id';

    // 追加字段
    // protected $append = [''];

    /**
     * [filter 查询条件过滤器]
     * Author：上官钧墨
     * @return $data [被过滤数组]
     */
    private function filter($data=[])
    {
 		// 设置要查询的字段
    	$default = [
    		'admin_user_id'=>'',
    		'user_name'=>'',
    	];
    	if (count($data)<1) {
    		return [];
    	}
    	// 合并数据，以设置为准
    	$params = $this->setDefaultValue($data,$default);
    	$filter = [];
    	// 更多查询条件......
    	!empty($params['admin_user_id']) && $filter[] = ['admin_user_id', '=', $params['admin_user_id']];
        !empty($params['user_name']) && $filter[] = ['user_name', 'like', "%{$params['user_name']}%"];

        return $filter;

    }

    /**
     * [getList 获取]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function getList($data)
    {
        $hidden = ['password'];
        $page = 1;//设置页码
		$listRows = 15;//设置每页条数

		isset($data['page']) && !empty((int)$data['page'])?$page = $data['page']:$page;
		isset($data['listRows']) && !empty((int)$data['listRows'])?$page = $data['listRows']:$page;

		$model = $this->where($this->filter($data));
		$total = $model->count();
        $list = $model->page($page,$listRows)->hidden($hidden)->select();

        $RoleMenu = new AdminUserRoleModel;
        $allMenuApi = $RoleMenu->where([])->hidden(['create_time'])->select();

        $AdminRole = new AdminRoleModel;
        $allTree = $AdminRole->allTree();

        foreach ($list as $key => $value) {
        	$apiIds = $this->apiIds($allMenuApi,$allTree,$value['admin_user_id']);
            $list[$key]['apiIds'] = $apiIds['apiIds'];
            $list[$key]['user_role'] = $apiIds['user_role'];
            unset($apiIds);
        }
        return ['page'=>$page,'total'=>$total,'listRows'=>$listRows,'list'=>$list];
    }
    /**
     * [apiIds 获取已分配的id]
     * Author：上官钧墨
     * @param  [type] $list          [所有关系数据]
     * @param  [type] $allTree       [所有分组数据]
     * @param  [type] $admin_user_id [管理员id]
     */
    private function apiIds($list,$allTree,$admin_user_id){
        $apiIds = [];
        $role = [];
        foreach ($list as $k => $item) {
            if ($item['admin_user_id'] == $admin_user_id) {
                array_push($apiIds,$item['admin_role_id']);
            }
        }
        
        foreach ($allTree as $key => $item) {
        	if (in_array($item['admin_role_id'],$apiIds)) {
            	array_push($role,[
            		'admin_role_id'=>$item['admin_role_id'],
            		'name'=>$item['name']
            	]);
            }
        }
        return ['apiIds'=>$apiIds,'user_role'=>$role];
    }

    /**
     * [add 新增]
     * Author：上官钧墨
     * @param [type] $data [description]
     */
    public function add($data=[])
    {
        $newData['user_name'] = $data['user_name'];
        $newData['password'] = pwd($data['password']);
        $newData['is_super'] = $data['is_super']?1:0;
        $newData['status'] = $data['status']?1:0;
        $newData['create_time'] = time();
        $newData['update_time'] = time();

        $detail = $this->detail(['user_name'=>$data['user_name']]);
        if ($detail) {
        	$this->error = '新增失败，登录名已经存在';
            return false;
        }

        $this->startTrans();
        $admin_user_id = $this->insertGetId($newData);
        if (!$admin_user_id) {
            $this->rollback();
            $this->error = '新增失败，请重试';
            return false;
        }
        $arr = [];
        $apiIds = $data['apiIds'];
        foreach ($apiIds as $key => $admin_role_id) {
            $arr[$key] = [
                'admin_user_id'=>$admin_user_id,
                'admin_role_id'=>$admin_role_id,
                'create_time'=>time()
            ];
        }
        if (count($arr)<1) {
            $this->commit();
            return true;
        }
        
        $UserRole = new AdminUserRoleModel;
        $res = $UserRole->insertAll($arr);
        if (!$res) {
            $this->rollback();
            $this->error = '新增失败，请重试 -1';
            return false;
        }
        $this->commit();
        return true;
    }

    /**
     * [edit 编辑]
     * Author：上官钧墨
     * @param  [type] $data [更新数据]
     */
    public function edit(array $data=[],$info)
    {
        $arr = [];
        foreach ($data['apiIds'] as $key => $admin_role_id) {
            array_push($arr,[
                'admin_user_id'=>$data['admin_user_id'],
                'admin_role_id'=>$admin_role_id,
                'create_time'=>time()
            ]);
        }

        if ($info['user_name'] != $data['user_name']) {
            $find = $this->detail(['user_name'=>$data['user_name']]);
	        if ($find) {
	        	$this->error = '编辑失败，登录名已经存在';
	            return false;
	        }
        }
        $newData['user_name'] = $data['user_name'];
        if ($data['password']) {
        	$newData['password'] = pwd($data['password']);
        }
        $newData['is_super'] = $data['is_super']?1:0;
        $newData['status'] = $data['status']?1:0;
        $newData['update_time'] = time();

        // 超管为1的直接更新，无需关系
        if ($data['is_super']) {
	        $resSave = $this->save($newData);
	        if (!$resSave) {
	            $this->error = '修改失败，请重试 -2';
	            return false;
	        }
	        return true;
        }

        // 思路：先删除原有的关系，再新增关系
        $RoleMenu = new AdminUserRoleModel;
        $RoleMenu->startTrans();
        $detail = $RoleMenu->where(['admin_user_id'=>$data['admin_user_id']])->select();
        if (count($detail)>0) {
            $resDel = $detail->delete();
            if (!$resDel) {
                $RoleMenu->rollback();
                $this->error = '修改失败，原关系清除失败';
                return false;
            }
        }
        if ($arr) {
            $res = $RoleMenu->insertAll($arr);
            if (!$res) {
                $RoleMenu->rollback();
                $this->error = '修改失败，请重试';
                return false;
            }
        }

        
        $resSave = $this->save($newData);
        if (!$resSave) {
            $this->error = '修改失败，请重试 -1';
            return false;
        }
        $RoleMenu->commit();
        return true;
    }

    /**
     * [del 删除]
     * Author：上官钧墨
     */
    public function del($data)
    {
        $menuApiModel = new AdminUserRoleModel;
        $menuApiModel->startTrans();
        $detail = $menuApiModel->where([$this->pk=>$this[$this->pk]])->select();
        if (count($detail)>0) {
            $find = $detail->delete();
	        if (!$find) {
	        	$menuApiModel->rollback();
	            $this->error = '删除失败，关系清除失败';
	            return false;
	        }
        }
        $resDel = $this->delete();
        if (!$resDel) {
        	$menuApiModel->rollback();
            $this->error = '删除失败，请重试';
            return false;
        }
        $menuApiModel->commit();
        return true;
    }
    /**
     * [detail 获取详情]
     * Author：上官钧墨
     * @param  [type] $where [条件]
     */
    public function detail($where=[], $with = [],$hidden = [])
    {
        is_array($where) ? $filter = $where : $filter[$this->pk] = (int)$where;
        return $this->get($filter, $with,$hidden);
    }
}